import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user_name: JSON.parse(sessionStorage.getItem('user_name')),
    token: sessionStorage.getItem('token'), // 保存token字符串
  },
  getters: {
  },
  mutations: {
    saveToken(state, token) {
      state.token = token
      sessionStorage.setItem("token", token)
    },
    updateUser(state, payload) {
      state.user_name = payload
      // 为了数据持久化保存，还需要向storage中存一份user
      sessionStorage.setItem('user_name', JSON.stringify(payload))
    }
  },
  actions: {
    loginAndSaveUser(store, payload) {
      // 发送登录请求 
      // ......
      // ......
      // ......
      //获取到登录结果后
      store.commit('updateUser', { user_name: 'user_name' })
    }
  },
  modules: {
  }
})
